<template>
  <div class="body">
    <p class="title">账户管理</p>
    <!-- 输入框内容 -->
    <div class="search_box">
      <div class="input_box">
        <el-input class="element_input" v-model="searchName" placeholder="请输入账户名称" @input="searchData"></el-input>
        <el-button type="primary" class="new_btn" @click="addShow(formRef)">新增</el-button>
      </div>
    </div>

    <el-table :data="pageCount" border="1px solid black" stripe="boolean" style="width: 100%; margin-top: 20px;"
      @selection-change="">
      <el-table-column prop="id" label="序号" width="78" align="center"></el-table-column>
      <el-table-column prop="account" label="账户名称" align="center"></el-table-column>
      <el-table-column prop="img" label="账户头像" align="center">
        <template #default="scope">
          <!-- <div class="demo-image__preview">
            <el-image style="width: 50px; height: 50px" :src="scope.row.imgs" :zoom-rate="1.2" :max-scale="7"
              :min-scale="0.2" preview-teleported :preview-src-list="[scope.row.imgs]" show-progress :initial-index="4"
              fit="cover" />
          </div> -->
          <div class="demo-image__preview">
            <el-image style="width: 40px; height: 40px" :src="scope.row.imgs" :zoom-rate="1.2" :max-scale="7"
            :min-scale="0.2" :preview-src-list="[scope.row.imgs]" show-progress fit="cover" preview-teleported />
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="type" label="角色类型" align="center">
        <template #default="scope">
          <div style="display: flex; align-items: center;justify-content: center;">
            <div class="type_text">
              {{
                scope.row.type === 1 ? '超管' :
                  scope.row.type === 2 ? '劳务公司' :
                    scope.row.type === 4 ? '审核员' :
                      '未知类型'
              }}
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="角色名称" align="center"></el-table-column>
      <el-table-column prop="status" label="状态" align="center">
        <template #default="scope">
          <el-switch v-model="scope.row.status" @change="statusChange(scope.row)" :active-value="1" :inactive-value="0"
            inline-prompt active-text="开启" inactive-text="关闭" />
        </template>
      </el-table-column>
      <el-table-column prop="create_time" label="创建时间" align="center"></el-table-column>
      <el-table-column label="操作" width="170" align="center">
        <template #default="scope">
          <div style="display: flex; align-items: center;justify-content: center;">
            <el-button class="btn" type="primary" @click="editPop(scope.row)">编辑</el-button>
            <el-button class="btn" v-if="scope.row.id !== 1" @click="deletePopShow(scope.row.id)"
              type="danger">删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div class="page_box">
      <el-pagination @size-change="pageNum" @current-change="pageChange" :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100, 200]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
        :total="pageData.length" />
    </div>
    <div class="bottom_box"></div>
    <el-dialog v-model="dialogVisible" title="添加账号" width="1000">
      <el-form ref="formRef" :model="employeeForm" :rules="formRules">
        <el-form-item prop="account" label="账号名称">
          <div class="form_row">
            <!-- 姓名输入框 -->
            <el-input v-model="employeeForm.account" :disabled="editStatus" class="form_input" placeholder="请输入账户名称"
              clearable />
          </div>
        </el-form-item>
        <el-form-item prop="type" label="账户角色">
          <div class="form_row">
            <!-- 姓名输入框 -->
            <el-select class="form_input" :disabled="editStatus" v-model="employeeForm.type" clearable
              placeholder="请选择账户角色">
              <el-option label="劳务公司" :value="2"></el-option>
              <el-option label="薪资审核员" :value="4"></el-option>
            </el-select>
          </div>
        </el-form-item>
        <el-form-item prop="pass" label="账户密码" v-if="editStatus == false">
          <div class="form_row">
            <!-- 姓名输入框 -->
            <el-input class="form_input" v-model="employeeForm.pass" placeholder="请输入账户密码" clearable />
          </div>
        </el-form-item>
        <el-form-item prop="password" label="确认密码" v-if="editStatus == false">
          <div class="form_row">
            <!-- 姓名输入框 -->
            <el-input class="form_input" v-model="employeeForm.password" placeholder="请输入确认密码" clearable />
          </div>
        </el-form-item>
        <el-form-item label="账户密码" v-if="editStatus">
          <div class="form_row">
            <!-- 姓名输入框 -->
            <el-input class="form_input" v-model="employeeForm.account_pass" placeholder="账户密码" clearable />
          </div>
        </el-form-item>
        <el-form-item prop="imgs" label="账户头像">
          <div class="avatar-uploader">
            <el-upload action="#" list-type="picture-card" :auto-upload="false" :limit="1" :on-change="handleFileChange"
              :on-remove="handleRemove" :file-list="fileList" :class="{ 'hide-upload': fileList.length > 0 }">
              <template v-if="fileList.length === 0">
                <el-icon>
                  <Plus />
                </el-icon>
              </template>
              <template v-else>
                <img class="avatar" :src="fileList[0].url" alt="头像" />
                <span class="avatar-actions">
                  <span class="avatar-preview" @click.stop="handlePictureCardPreview(fileList[0])">
                    <el-icon>
                      <ZoomIn />
                    </el-icon>
                  </span>
                  <span class="avatar-delete" @click.stop="handleRemove(fileList[0])">
                    <el-icon>
                      <Delete />
                    </el-icon>
                  </span>
                </span>
              </template>
            </el-upload>
          </div>
        </el-form-item>

        <el-dialog v-model="imgStatus">
          <img w-full :src="dialogImageUrl" alt="预览图片" style="max-width: 100%">
        </el-dialog>
        <!-- 管理费 -->
        <el-form-item v-if="editStatus">
          <div style="display: flex; justify-content: space-between;">
            <div class="form_row" style="margin-left: -9px;">
              管理费-长期
              <div style="width: 10px;"></div>
              <el-input style="width: 200px" v-model="employeeForm.manage_p" class="form_input" type="number"
                placeholder="管理费-长期" />
            </div>
            <div style="width: 20px;"></div>
            <div class="form_row" style="margin-left: -9px;">
              管理费-短期
              <div style="width: 10px;"></div>
              <el-input style="width: 200px" v-model="employeeForm.manage_l" class="form_input" type="number"
                placeholder="管理费-短期" />
            </div>
            <div style="width: 20px;"></div>
            <div class="form_row" style="margin-left: -9px;">
              管理费-学员
              <div style="width: 10px;"></div>
              <el-input style="width: 200px" v-model="employeeForm.manage_x" class="form_input" type="number"
                placeholder="管理费-学员" />
            </div>
          </div>
        </el-form-item>
        <el-form-item>
          <div class="form_row">
            <p class="required-mark">*</p>
            <p>账号状态</p>
            <div style="width: 10px;"></div>
            <el-switch class="form_input" v-model="addStatus" :active-value="true" :inactive-value="false" inline-prompt
              active-text="开启" inactive-text="关闭" />
          </div>
        </el-form-item>
        <el-form-item>
          <div class="form_row">
            <!-- 姓名输入框 -->
            <p class="required-mark">*</p>
            <p>确认详情</p>
            <div class="editor-container layout-pd form_input">
              <Editor />
            </div>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closePop">取消</el-button>
          <el-button type="primary" @click="appendData(formRef)">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 删除弹窗显示 -->
    <el-dialog v-model="deletePop" title="删除员工" width="500">
      <div class="delete_title">
        <img src="/src/assets/warn.png" alt="">
        <span>确定要删除这些员工吗?</span>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="deletePop = false">取消</el-button>
          <el-button type="primary" @click="deleteAffirm">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, reactive, defineAsyncComponent } from 'vue';// 引入ref和computed
import { accountAdd, accountList, imgFile, accountDel } from '/@/api/login/index';//引入当前的接口封装
import type { FormInstance, FormRules, UploadFile, } from 'element-plus'
import { ElMessage } from 'element-plus';
import { Delete, Plus, ZoomIn } from '@element-plus/icons-vue'
const dialogVisible = ref(false)
// 引入组件
const Editor = defineAsyncComponent(() => import('/@/components/editor/index.vue'));
// 全部数据
const data = ref<any[]>([]);
const pageData = ref<any[]>([]);
// 声明当前的页码
const currentPage = ref(1);
// 声明当前页面渲染的数据条数
const pageSize = ref(10);
// 搜索输入框
const searchName = ref('');
// 图片上传
const fileList = ref<UploadFile[]>([])  // 关键：维护文件列表
// 图片预览的路径
const dialogImageUrl = ref(<any>[]);
// 图片预览显示状态
const imgStatus = ref(false);
// 账户列表请求接口
const addStatus = ref(false || true);
// 编辑状态
const editStatus = ref(false);
// 编辑id
const editId = ref('');
accountList().then(res => {
  console.log(res);
  data.value = res.data;
  pageData.value = res.data;
})

// 计算分页数据
const pageCount = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return pageData.value.slice(start, end);
});

// 页码改变事件
const pageChange = (val: any) => {
  currentPage.value = val;
};

// 每页条数改变事件
const pageNum = (val: any) => {
  pageSize.value = val;
  currentPage.value = 1; // 重置到第一页
};

// 搜索函数
const searchData = () => {
  const filteredData = computed(() => {
    // 无搜索词时返回全部数据
    if (!searchName.value) {
      return pageData.value = data.value;
    }
    console.log(searchName.value);

    return data.value.filter(item => {
      // 检查每个字段是否满足相应条件（如果该搜索条件存在）
      const nameMatch = !searchName.value ||
        (item.account && item.account.toString().toLowerCase().includes(searchName.value.toLowerCase()));

      return nameMatch;
    });
  });
  pageData.value = filteredData.value;
};

const handlePictureCardPreview = (file: UploadFile) => {//图片预览
  dialogImageUrl.value = file.url;
  imgStatus.value = true;
}

const handleFileChange = (file: UploadFile) => {
  // 创建本地预览
  file.url = URL.createObjectURL(file.raw!);
  fileList.value = [file];

  // 上传到服务器
  const formData = new FormData();
  formData.append('file', file.raw!);

  imgFile(formData).then(res => {
    employeeForm.imgs = res.url;
  }).catch(err => {
    fileList.value = [];
    employeeForm.imgs = '';
    ElMessage.error('上传失败');
  });
};

const handleRemove = (file?: UploadFile) => {
  fileList.value = [];
  employeeForm.imgs = '';
};


// 定义表单数据类型
interface EmployeeForm {
  // 账户名称
  account: string;
  // 角色类型
  type: number | null;
  // 密码
  pass: string;
  // 二次确认
  password: string;
  // 图片
  imgs: string;
  // 管理费-长期
  manage_p: number;
  // 管理费-短期
  manage_l: number;
  // 管理费-学员
  manage_x: number;
  // 账户密码
  account_pass: string;
}

// 初始化表单数据
const employeeForm = reactive<EmployeeForm>({
  account: '',
  type: null,
  pass: '',
  password: '',
  imgs: '',
  manage_p: 0,
  manage_l: 0,
  manage_x: 0,
  account_pass: ''
})
const formRef = ref<FormInstance>();
// 表单验证规则
const formRules = reactive<FormRules<EmployeeForm>>({
  account: [
    { required: true, message: '请输入账户名称', trigger: 'blur' },
    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' },
  ],
  type: [
    { required: true, message: '请选择账户角色', trigger: 'blur' },
  ],
  pass: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 18, message: '长度在 6 到 18 个字符', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入确认密码', trigger: 'blur' },
    { min: 6, max: 18, message: '长度在 6 到 18 个字符', trigger: 'blur' },
  ],
  imgs: [
    { required: true, trigger: 'change', message: '请上传图片' }
  ]
})
// 添加确认点击事件
const appendData = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      const formData = {
        id: editId.value,
        account: employeeForm.account,
        type: employeeForm.type,
        roleid: employeeForm.type,
        password: employeeForm.password,
        img: employeeForm.imgs,
        status: addStatus ? 2 : 1,
        pid: 0,
        manage_p: employeeForm.manage_p,
        manage_l: employeeForm.manage_l,
        manage_x: employeeForm.manage_x,
      }
      accountAdd(formData).then(res => {
        if (res.code == 1) {
          ElMessage.success('操作成功');
          dialogVisible.value = false;
          // 重置表单
          formRef.value?.resetFields();
        } else {
          ElMessage.error('操作失败');
        }
      }).catch(err => {
        ElMessage.error(err);
      })
    }
  })
}
// 关闭弹窗按钮
const closePop = () => {
  dialogVisible.value = false;
  formRef.value?.resetFields();
}
// 编辑显示弹窗
const editPop = (item: any) => {
  console.log(item);
  fileList.value = 'http://labour_admin.kuxia.top' + item.img
    ? [
      {
        uid: Date.now(),
        name: 'avatar',
        url: 'http://labour_admin.kuxia.top' + item.img,
        status: 'success',
      },
    ]
    : [];
  editId.value = item.id;
  dialogVisible.value = true;
  editStatus.value = true;
  employeeForm.account = item.account;
  employeeForm.type = item.type;
  employeeForm.manage_p = item.manage_p;
  employeeForm.manage_l = item.manage_l;
  employeeForm.manage_x = item.manage_x;
  addStatus.value = item.status == 1 ? true : false;
  employeeForm.imgs = item.img;
}
// 删除弹窗状态
const deletePop = ref(false);
const deleteId = ref(0);
const deletePopShow = (item: any) => {
  deletePop.value = true;
  deleteId.value = item;
};

// 删除确认事件
const deleteAffirm = () => {
  accountDel({ id: deleteId.value }).then(res => {
    if (res.code == 1) {
      ElMessage.success('删除成功');
      deletePop.value = false;
    }
  }).catch(err => {
    ElMessage.error(err);
  })
}

// 状态修改事件
const statusChange = (item: any) => {
  const formData = {
    id: item.id,
    account: item.account,
    type: item.type,
    roleid: item.type,
    password: item.password,
    img: item.img,
    status: item.tatus == 1 ? 2 : 1,
    pid: 0,
    manage_p: item.manage_p,
    manage_l: item.manage_l,
    manage_x: item.manage_x,
  }
  accountAdd(formData).then(res => {
    if (res.code == 1) {
      ElMessage.success('修改成功');
      dialogVisible.value = false;
      // 重置表单
      formRef.value?.resetFields();
    } else {
      ElMessage.error('修改失败');
    }
  }).catch(err => {
    ElMessage.error(err);
  })
}

const addShow = (formEl: FormInstance | undefined) => {
  dialogVisible.value = true;
  editStatus.value = false;
  fileList.value = [];
  if (!formEl) return;
  formEl?.resetFields();
}

</script>

<style scoped>
.body {
  padding: 20px;
}

.item {
  margin-top: 10px;
  margin-right: 40px;
}

.title {
  font-weight: 400;
  font-size: 25px;
}

.input_box {
  width: 100%;
  display: flex;
  margin-top: 15px;
  align-items: center;
  justify-content: space-between;
}

.element_input {
  width: 15%;
}

.new_btn {
  height: 35px;
  margin-left: 5%;
  background-color: #0052CC;
  border: 1px solid #0052CC;
}

.new_btn:hover {
  background-color: #4d82d1;
  border: 1px solid #4d82d1;
}

.new_btn:active {
  background-color: #00388b;
  border: 1px solid #00388b;
}

.type_text {
  padding: 5px 10px;
  background-color: #ECF5FF;
  border: 1px solid #469dff;
  color: #469dff;
  border-radius: 5px;
}

.avatar {
  width: 50px;
  height: 50px;
}

.page_box {
  margin-top: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.bottom_box {
  width: 100%;
  height: 30px;
}

.demo-image__error .el-image {
  width: 100%;
  height: 200px;
}

.form_row {
  width: 100%;
  display: flex;
  line-height: 40px;
}

.form_input {
  width: 85%;
}

.required-mark {
  color: red;
  margin-right: 5px;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.delete_title {
  display: flex;
}

.delete_title img {
  width: 20px;
  margin-right: 10px;
}

.btn {
  height: 30px;
  padding: 0px 15px;
}

.avatar-uploader {
  position: relative;
  display: inline-block;
}

.avatar-uploader :deep(.el-upload) {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader :deep(.el-upload:hover) {
  border-color: var(--el-color-primary);
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-actions {
  position: absolute;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  background: rgba(0, 0, 0, 0.5);
  opacity: 0;
  transition: opacity var(--el-transition-duration-fast);
}

.avatar-actions:hover {
  opacity: 1;
}

.avatar-actions span {
  margin: 0 5px;
  color: white;
  font-size: 1.2em;
  cursor: pointer;
}

/* 隐藏上传按钮当有图片时 */
.hide-upload :deep(.el-upload) {
  display: none;
}

/* 在全局或组件样式添加 */
.avatar-uploader :deep(.el-upload-list__item) {
  transition: none !important;
}
</style>